import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_caijinglong_examples/widget/my_app_bar.dart';
import 'package:provider/provider.dart';

class SliverListExample extends StatefulWidget {
  const SliverListExample({super.key});

  @override
  State<SliverListExample> createState() => _SliverListExampleState();
}

class _SliverListExampleState extends State<SliverListExample> {
  final DataNotifier notifier = DataNotifier();

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<DataNotifier>.value(
      value: notifier,
      child: Scaffold(
        appBar: MyAppBar(child: widget),
        body: CustomScrollView(
          slivers: <Widget>[
            _buildBody(),
          ],
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            notifier.addData();
          },
        ),
      ),
    );
  }

  Widget _buildBody() {
    return Selector<DataNotifier, int>(
      selector: (context, value) {
        return value.data.length;
      },
      builder: (BuildContext context, int value, Widget? child) {
        return SliverList(
          delegate: SliverChildBuilderDelegate(
            _buildItem,
            childCount: notifier.data.length,
          ),
        );
      },
    );
  }

  Widget _buildItem(BuildContext context, int index) {
    return ListTile(
      title: Text(notifier.data[index]),
    );
  }
}

class DataNotifier extends ChangeNotifier {
  List<String> data = [];

  void addData() {
    data.insert(0, Random().nextInt(302300).toString());
    notifyListeners();
  }
}
